-module(tictactoe).
-export([tictactoe/1, horizontals/1, verticals/1, diagonals/1, all_lines/1]).

tictactoe(Board) ->
    Lines = all_lines(Board),
    tictactoe_ver2(Lines, cat).

tictactoe_ver2([[P, P, P]|_], _) when P /= e ->
    P;
tictactoe_ver2([[A,B,C]|Rest], NoWinnerAcc) ->
    tictactoe_ver2(Rest, 
		   case lists:any(fun(X) -> X == e end, [A, B, C]) of
		       true ->  no_winner;
		       _ -> NoWinnerAcc
		   end);
tictactoe_ver2([], NoWinnerAcc) ->
    NoWinnerAcc.
    
all_lines(L) ->
    diagonals(L) ++ horizontals(L) ++ verticals(L).

horizontals([A, B, C|Rest]) ->    
    [[A, B, C]|horizontals(Rest)];
horizontals([]) ->
    [].

verticals([A, B, C|Rest]) ->
    verticals(Rest, [[A], [B], [C]]).

verticals([A, B, C|Rest], [Acc1, Acc2, Acc3]) ->
    verticals(Rest, [[A|Acc1], [B|Acc2], [C|Acc3]]);
verticals([], Acc) ->
    Acc.

diagonals([TL, _, TR, _, M, _, BL, _, BR]) ->
    [[TL, M, BR], [TR, M, BL]].
